package com.xmmxjy.config;

import com.google.common.collect.Range;
import com.xiaoleilu.hutool.date.DateUtil;
import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.RangeShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import io.shardingsphere.api.algorithm.sharding.standard.RangeShardingAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 自定义范围分片算法
 * @author xmm
 */
public class MyRangeShardingAlgorithm implements RangeShardingAlgorithm<Date> {
    private Logger logger = LoggerFactory.getLogger(MyRangeShardingAlgorithm.class);

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Date> shardingValue) {
        List<String> list = new ArrayList<>();
        logger.info("availableTargetNames : " + availableTargetNames);
        logger.info(shardingValue.toString());
        Range<Date> valueRange = shardingValue.getValueRange();
        Date lowerDate = valueRange.lowerEndpoint();
        int lowerMonth = DateUtil.month(lowerDate) + 1;
        Date upperDate = valueRange.upperEndpoint();
        int upperMonth = DateUtil.month(upperDate) + 1;
        List<Integer> monthList = new ArrayList<>();
        for (int i = lowerMonth; i <= upperMonth; i++) {
            monthList.add(i);
        }
        for (String tableName : availableTargetNames) {
            for (int month : monthList) {
                String indexStr = tableName.substring(tableName.lastIndexOf("_") + 1);
                int index = Integer.parseInt(indexStr);
                if (index == month) {
                    list.add(tableName);
                    break;
                }
            }
        }
        System.out.println(list);
        return list;
    }
}
